$(document).ready(function() {
	//~jq-ui的tab初始化=====================================================================
	$( "#dish-tabs" ).tabs({
		active: 0,
		beforeLoad: function( event, ui ) {
			ui.jqXHR.error(function() {
				ui.panel.html("该页面不存在");
			});
		}
	});
	
	//~数据绑定操作=====================================================================
	var blankDish = {
		id: "0",
		name: "",
		price: "",
		discount: "",
		priceDiscounted: "",
		intro: "",
		desc: "",
		activity: {
			id: undefined,
			name: ""
		},
		provideTimes: [
			{
				id: "0",
				startTime: "0:00:00",
				endTime: "0:00:00",
				dayOfWeek: "0"
			}
		]
	};
	
	var dishCreateModel = function(dishModel) {
		var self = this;
		self.dish = ko.mapping.fromJS(dishModel);
		self.filePath = ko.observable('default.jpg');
		self.addPTime = function() {
			self.dish.provideTimes.push(ko.mapping.fromJS(blankDish.provideTimes[0]));
		};
		self.removePTime = function(pTime) {
			//console.log(pTime);
			self.dish.provideTimes.remove(pTime);
		};
		self.activitiesSel = ko.observableArray([]);
		//绑定改变活动之后菜式的折扣改变
		ko.computed(function() {
			var activities = self.activitiesSel();
			var activityId = self.dish.activity.id();
			var len = activities.length;
			if (parseInt(activityId) > 0) {
				for (var i = 0; i < len;i++) {
					var myActivity = activities[i];
					if (myActivity.id == activityId) {
						self.dish.discount(myActivity.defaultDiscount);
					}
				}
			} else {
				self.dish.discount(10);
			}
		});
		//绑定单价和折扣改变之后总价改变
		ko.computed(function() {
			var dishPrice = parseFloat(self.dish.price());
			if (!(dishPrice >= 0)) {
				self.dish.price(0);
			} else {
				self.dish.price(roundNumber(dishPrice, 2));
			}
			var disCount = parseFloat(self.dish.discount());
			if (!(disCount > 0 && disCount <= 10)) {
				self.dish.discount('10.0');
			} else {
				self.dish.discount(roundNumber(disCount, 1));
			}
			var priceDiscounted = roundNumber(self.dish.price() * self.dish.discount() / 10, 2);
			self.dish.priceDiscounted(priceDiscounted);
		});
		//时间格式化补全
		ko.computed(function(){
			var pTimes = self.dish.provideTimes();
			var timesLen = pTimes.length;
			var changeTimeFormat = function(time) {
				if (time.length == 0) time = '0';
				while (time.split(':').length < 3) {
					time = time + ':00';
				};
				return time;
			};
			for (var i = 0; i < timesLen;i++) {
				var pTime = pTimes[i];
				pTime.startTime(changeTimeFormat(pTime.startTime()));
				pTime.endTime(changeTimeFormat(pTime.endTime()));
			}
		});
		$.getJSON('../activity/all/simple', function(response) {
			//console.log(response);
			self.activitiesSel(response.activities);
		});
		self.createDish = function() {
			var dish = ko.mapping.toJS(self.dish);
			var pTimes = dish.provideTimes;
			var len = pTimes.length;
			//console.log(len);
			for (var i = 0; i < len; i++) {
				var pTime = pTimes[i];
				//菜式提供时间是周一到周五
				
				if (pTime.dayOfWeek == '8') {
					var startTime = pTime.startTime;
					var endTime = pTime.endTime;
					delete pTimes[i];
					for (var j = 0; j < 5; j++) {
						pTimes.push({
							id: "0",
							startTime: startTime,
							endTime: endTime,
							//周一到周五
							dayOfWeek: j + 1
						});
					}
				}
				//菜式提供时间是每天
				if (pTime.dayOfWeek == '9') {
					var startTime = pTime.startTime;
					var endTime = pTime.endTime;
					delete pTimes[i];
					for (var j = 0; j < 7; j++) {
						pTimes.push({
							id: "0",
							startTime: startTime,
							endTime: endTime,
							//周一到周五
							dayOfWeek: j + 1
						});
					}
				}
			}
			//console.log(dish);
			$.ajax({
				type: 'post',
				url: 'dish/create?dishImgPath=' + self.filePath(),
				contentType: "application/json",//application/xml
				processData: true,//contentType为xml时，些值为false
				dataType: "json",//json--返回json数据类型；xml--返回xml
				data: JSON.stringify(dish),
				success: function(response) {
					if (response.success == true) {
						alert('创建菜式成功');
						ko.mapping.fromJS(blankDish, self.dish);
					}
				},            
				error:function(e){
				}
			});
		};
	};

	var dishModel = new dishCreateModel(blankDish);
	ko.applyBindings(dishModel, document.getElementById('add-dish-tab'));
	
	//~上传图片操作=====================================================================
	// 全局配置（这样就不必每次初始化时都加上下面的设置）
	$.jUploader.setDefaults({
	    cancelable: true, // 可取消上传
	    allowedExtensions: ['jpg', 'png', 'gif'], // 只允许上传图片
	    messages: {
	        upload: '上传图片',
	        cancel: '取消上传',
	        emptyFile: "{file} 为空，请选择一个文件.",
	        invalidExtension: "{file} 后缀名不合法. 只有 {extensions} 是允许的.",
	        onLeave: "文件正在上传，如果你现在离开，上传将会被取消。"
	    }
	});

	$.jUploader({
	    button: 'uploadbutton', // 这里设置按钮id
	    action: 'dish/dishimgupload', // 这里设置上传处理接口
	
	    // 开始上传事件
	    onUpload: function (fileName) {
	        $('#uploadinfo').text('正在上传 ' + fileName + ' ...');
	    },
	
	    // 上传完成事件
	    onComplete: function (fileName, response) {
	        // response是json对象，格式可以按自己的意愿来定义，例子为： { success: true, fileUrl:'' }
	        if (response.success) {
	            //$('#headportraitimg').attr('src', '../img/dishimgtemp/' + response.path);
	            $('#uploadinfo').text(fileName + ' 上传成功。');
	            dishModel.filePath(response.path);
	        } else {
	            $('#uploadinfo').text('上传失败');
	        }
	    },
	
	    // 取消上传事件
	    onCancel: function (fileName) {
	        $('#uploadinfo').text(fileName + ' 上传取消。');
	    },
	
	    // 系统信息显示（例如后缀名不合法）
	    showMessage: function (message) {
	        alert(message);
	    }
	});
});